//package com.ftt;
//import javax.servlet.ServletException;
//import javax.servlet.annotation.WebServlet;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//@WebServlet("/register.do")
//public class RegisterServlet extends HttpServlet {
//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//String username = req.getParameter("username");
//String  email = req.getParameter("email");
//String password = req.getParameter("password");
//String confirmPassword = req.getParameter("confirmPassword");
//if(password.equals(confirmPassword) ){
//req.getRequestDispatcher("index.jsp").forward(req,resp);
//    }else{
//resp.sendRedirect("注册.jsp");}
//    }
//}


package com.ftt;

import java.io.IOException;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //1、获取数据库连接
        Connection conn = DBUtile.getConnection();
        String sql1 = "select * from tb_manager where name=?";
        PreparedStatement ps1 = null;

        try {
            ps1 = conn.prepareStatement(sql1);
            ps1.setString(1, username);
            ResultSet rs1= ps1.executeQuery();
            if (rs1.next()) {
                req.setAttribute("errorMessage", "用户已存在，请直接登录。");
                req.getRequestDispatcher("登录.jsp").forward(req,resp);


            } else {
                String sql = "INSERT INTO tb_manager (`name`,`password`) VALUES (?, ?)";
                //2、获取操作对象
                PreparedStatement ps = null;
                try {
                    ps = conn.prepareStatement(sql);
                    ps.setString(1, username);
                    ps.setString(2, password);
                    int n = ps.executeUpdate();
                    if (n > 0) {
                        req.getRequestDispatcher("登录.jsp").forward(req,resp);
                    } else {
                        resp.sendRedirect("register.jsp");
                    }
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }catch(SQLException e) {
            e.printStackTrace();
            System.out.println("数据库获取失败");
        }                //3、关闭资源
        DBUtile.closeResource(conn, ps1, null);
    }
}


